package com.siwei.mes.service.system.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.siwei.mes.common.base.BaseParams;
import com.siwei.mes.common.query.PageQuery;
import com.siwei.mes.common.util.Md5Utils;
import com.siwei.mes.entity.system.ProjectArea;
import com.siwei.mes.entity.system.User;
import com.siwei.mes.enums.RoleEnum;
import com.siwei.mes.mapper.system.ProjectAreaMapper;
import com.siwei.mes.mapper.system.UserMapper;
import com.siwei.mes.service.system.AuthService;
import com.siwei.mes.service.system.UserService;
import com.siwei.mes.upload.devops.UploadDevopsService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.siwei.mes.common.exception.handler.MessageHandler.assertTrue;

/**
 * 用户表(User)表服务实现类
 *
 * @author linzi
 * @since 2023-11-25 18:16:11
 */
@Service
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private AuthService authService;
    @Resource
    private ProjectAreaMapper projectAreaMapper;
    @Resource
    private UploadDevopsService uploadDevopsService;

    @Override
    public Long create(User entity) throws NoSuchAlgorithmException {
        this.checkRolePermission();
        /**判断手机号是否存在*/
        assertTrue(userMapper.selectByUserPhone(entity.getUserPhone()) != null, "手机号已经存在!");
        entity.init(true);
        if (StringUtils.isBlank(entity.getPassword())) {
            entity.setPassword(BaseParams.PASSWORD);
        }
        /**这里md5加密一下*/
        entity.setPassword(Md5Utils.encrypt(entity.getPassword()));
        userMapper.insertSelective(entity);

        /**上传到运维系统*/
        uploadDevopsService.saveOrUpdateMesUser(entity.getUserPhone());
        return entity.getId();
    }

    @Override
    public void update(User entity) {
        if (!authService.getLoginUserId().equals(entity.getId())) {
            this.checkRolePermission();
        }
        entity.init(false);
        User user = userMapper.selectByPrimaryKey(entity.getId());
        assertTrue(user == null, "用户表信息不存在");
        if (!entity.getUserPhone().equals(user.getUserPhone())) {
            /**判断手机号是否存在*/
            assertTrue(userMapper.selectByUserPhone(entity.getUserPhone()) != null, "手机号已经存在");
        }
        userMapper.updateByPrimaryKeySelective(entity);

        /**上传到运维系统*/
        uploadDevopsService.saveOrUpdateMesUser(entity.getUserPhone());
    }

    @Override
    public void updatePassword(User entity) throws NoSuchAlgorithmException {
        this.checkRolePermission();
        entity.init(false);
        User user = userMapper.selectByPrimaryKey(entity.getId());
        assertTrue(user == null, "用户表信息不存在");
        assertTrue(!user.getPassword().equals(entity.getOldPassword()), "原密码错误");
        user.setPassword(Md5Utils.encrypt(entity.getPassword()));
        userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void delete(Long id) {
        this.checkRolePermission();
        User user = userMapper.selectByPrimaryKey(id);
        String idStr = String.valueOf(id);
        assertTrue(user == null, "用户表信息不存在");
        assertTrue(CollectionUtils.isNotEmpty(projectAreaMapper.getList(new ProjectArea().setHeadmanId(idStr))), "该用户为外检组长,请先变更巡查区域对应外检组长");
        List<ProjectArea> list = projectAreaMapper.getList(new ProjectArea().setCustomerServiceId(idStr));
        if (CollectionUtils.isNotEmpty(list)) {
            for (ProjectArea projectArea : list) {
                List<String> customerServiceIds = new ArrayList();
                List<String> customerServiceNames = new ArrayList();
                String[] userIds = projectArea.getCustomerServiceId().split(",");
                for (String userId : userIds) {
                    if (!userId.equals(idStr)) {
                        customerServiceIds.add(userId);
                    }
                }
                projectArea.setCustomerServiceId(String.join(",", customerServiceIds));
                String[] userNames = projectArea.getCustomerServiceName().split(",");
                for (String userName : userNames) {
                    if (!userName.equals(user.getUserName())) {
                        customerServiceNames.add(userName);
                    }
                }
                projectArea.setCustomerServiceName(String.join(",", customerServiceNames));
                projectAreaMapper.updateByPrimaryKey(projectArea);
            }
        }
        userMapper.deleteByPrimaryKey(id);

        /**上传到运维系统*/
        uploadDevopsService.deleteMesUser(user.getUserPhone());
    }

    @Override
    public PageInfo<User> getPage(PageQuery<User, User> query) {
        User searchParam = query.getParams();
        return PageHelper.startPage(query.getPageNum(), query.getPageSize())
                .doSelectPageInfo(() -> userMapper.getList(searchParam));
    }

    @Override
    public User loadById(Long id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<User> getAll(User entity) {
        if ("1".equals(entity.getIsArea())) {
            ProjectArea entityArea = new ProjectArea();
            entityArea.setHeadmanId(String.valueOf(authService.getLoginUserId()));
            if (StringUtils.isNotBlank(entity.getProjectArea())) {
                entityArea.setProjectArea(entity.getProjectArea());
                List<ProjectArea> list = projectAreaMapper.getList(entityArea);
                if (CollectionUtils.isNotEmpty(list)) {
                    List<String> ids = new ArrayList<>();
                    for (ProjectArea project : list) {
                        ids.addAll(Arrays.asList(project.getCustomerServiceId().split(",")));
                    }
                    ids.stream().distinct().collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(list)) {
                        entity.setIds(ids);
                    } else {
                        entity.setRoleId(Long.valueOf(RoleEnum.CUSTOMER_INSPECTOR.getCode()));
                    }
                } else {
                    entity.setRoleId(Long.valueOf(RoleEnum.CUSTOMER_INSPECTOR.getCode()));
                }
            } else {
                entity.setRoleId(Long.valueOf(RoleEnum.CUSTOMER_INSPECTOR.getCode()));
            }
        }
        return userMapper.getList(entity);
    }

    @Override
    public void updateUserSignImg(User entity) {
        entity.init(false);
        userMapper.updateByPrimaryKeySelective(entity);
    }

    @Override
    public Boolean getExperimentTypePermission(List<Integer> experimentTypeList) {
        if (experimentTypeList.isEmpty()) {
            return true;
        }
        Set<Integer> loginUserExperimentType = authService.getLoginUserExperimentType();
        /**判断用户的试验委托类型权限 是否包含查询条件的试验委托类型*/
        return loginUserExperimentType.containsAll(experimentTypeList);
    }

    public void checkRolePermission() {
        List<String> rolePermission = new ArrayList<>();
        rolePermission.add(RoleEnum.ADMIN.getCode());
        assertTrue(!rolePermission.contains(authService.getLoginUserRole()), "您暂无权限操作");
    }
}
